<template>
  <div>
    <!-- 只有店长能新增 -->
    <el-button v-if="isManager" type="primary" @click="openAdd">新增桌台</el-button>

    <el-table :data="tables" stripe style="margin-top:12px">
      <el-table-column prop="tableNumber" label="桌号" />
      <el-table-column label="状态">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'FREE' ? 'success' : 'danger'">
            {{ scope.row.status === 'FREE' ? '空闲' : '占用' }}
          </el-tag>
          <el-button
            v-if="isManager"
            size="small"
            style="margin-left:8px"
            @click="toggle(scope.row)"
          >
            切换
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 新增桌台弹窗 -->
  <el-dialog v-model="dialog" title="新增桌台" width="320px">
    <el-form :model="form" label-width="60">
      <el-form-item label="桌号">
        <el-input v-model="form.tableNumber" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialog=false">取消</el-button>
      <el-button type="primary" @click="submitAdd">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import request from '@/api/request'
import { raw } from '@/api/raw'
import { ElMessage } from 'element-plus'
import { jwtDecode } from 'jwt-decode'

interface Table {
  id: number
  tableNumber: string
  status: 'FREE' | 'OCCUPIED'
  storeId: number | null
}

const tables   = ref<Table[]>([])
const dialog   = ref(false)
const form     = ref({ tableNumber: '' })

/* 当前门店 & 角色 */
const auth     = useAuthStore()
const storeId  = ref<number | null>(null)
const isManager = ref(false)

onMounted(() => {
  const payload = jwtDecode(auth.token!) as any
  storeId.value   = payload.storeId
  isManager.value = payload.role === 3   // 3 = MANAGER
  loadTables()
})
const loadTables = () =>
  raw.get('/manager/tables', { params: { storeId: storeId.value } })
     .then(res => (tables.value = res.data))   // ⬅️ 多一层 .data
const openAdd = () => {
  form.value.tableNumber = ''   // 只清空桌号，不用关心 storeId
  dialog.value = true
}

const submitAdd = () => {
  const payload = jwtDecode(auth.token!) as any
  const curStoreId = payload.storeId
  if (!curStoreId) {
    ElMessage.error('无法获取门店ID，请重新登录')
    return
  }
  if (!form.value.tableNumber.trim()) {
    ElMessage.error('桌号不能为空')
    return
  }

  request.post('/manager/tables', {
    storeId: curStoreId,
    tableNumber: form.value.tableNumber.trim()
  }).then(() => {
    ElMessage.success('已添加')
    dialog.value = false
    loadTables()
  })
}

/* 切换状态（店长） */
const toggle = (row: Table) => {
  const newStatus = row.status === 'FREE' ? 'OCCUPIED' : 'FREE'
  request.patch(`/manager/tables/${row.id}/status`, { status: newStatus })
    .then(() => {
      ElMessage.success('已切换')
      loadTables()
    })
}
</script>